package com.ja.util;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {
	
	private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
			.setConnectionRequestTimeout(15000).build();

	private static HttpClientUtil instance = null;

	public HttpClientUtil() {
	}

	/**
	  * 方法名：getInstance 
	  * 描述：    创建类的实例                  
	  * 参数：    @return 
	 * @return: HttpClientUtil
	 */
	public static HttpClientUtil getInstance() {
		if (instance == null) {
			instance = new HttpClientUtil();
		}
		return instance;
	}

	/**
	 * 
	 * ----TODO：发送post请求
	 * 
	 */
	
	/**
	  * 方法名：sendHttpPost 
	  * 描述：     发送post请求                 
	  * 参数：    @param httpUrl
	  * 参数：    @return 
	 * @return: String
	 */
	public String sendHttpPost(String httpUrl) {
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
		return sendHttpPost(httpPost, "utf-8");
	}

	/**
	  * 方法名：sendHttpPost 
	  * 描述：    发送post请求                  
	  * 参数：    @param httpUrl
	  * 参数：    @param maps
	  * 参数：    @param type
	  * 参数：    @return 
	 * @return: String
	 */
	public String sendHttpPost(String httpUrl, Map<String, String> maps, String type) {
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();// 创建参数队列
		for (String key : maps.keySet()) {
			System.out.println(key+"-------------------key-------------"+maps.get(key)+"---------------maps.get(key)-------------------------------type---------"+type);
			nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, type));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sendHttpPost(httpPost, type);
	}

	/**
	  * 方法名：sendHttpPost 
	  * 描述：     发送post请求                 
	  * 参数：    @param httpPost
	  * 参数：    @param reponseType
	  * 参数：    @return 
	 * @return: String
	 */
	private String sendHttpPost(HttpPost httpPost, String reponseType) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			httpClient = HttpClients.createDefault();// 创建默认的httpClient实例.
			httpPost.setConfig(requestConfig);
			response = httpClient.execute(httpPost);// 执行请求
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, reponseType);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseContent;
	}

	
	/**
	 * 
	 * ----TODO：发送get请求
	 * 
	 */
	
	/**
	  * 方法名：sendHttpGet 
	  * 描述：    发送get请求                  
	  * 参数：    @param httpUrl
	  * 参数：    @return 
	 * @return: String
	 */
	public String sendHttpGet(String httpUrl) {
		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
		return sendHttpGet(httpGet);
	}

	/**
	  * 方法名：sendHttpGet 
	  * 描述：    发送 get请求                 
	  * 参数：    @param httpGet
	  * 参数：    @return 
	 * @return: String
	 */
	private String sendHttpGet(HttpGet httpGet) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			// 创建默认的httpClient实例.
			httpClient = HttpClients.createDefault();
			httpGet.setConfig(requestConfig);
			// 执行请求
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseContent;
	}

	/**
	  * 方法名：sendHttpsGet 
	  * 描述：    发送 get请求Https                  
	  * 参数：    @param httpUrl
	  * 参数：    @return 
	 * @return: String
	 */
	public String sendHttpsGet(String httpUrl) {
		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
		return sendHttpsGet(httpGet);
	}
	
	/**
	  * 方法名：sendHttpsGet 
	  * 描述：    发送 get请求Https                   
	  * 参数：    @param httpGet
	  * 参数：    @return 
	 * @return: String
	 */
	private String sendHttpsGet(HttpGet httpGet) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			// 创建默认的httpClient实例.
			PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader
					.load(new URL(httpGet.getURI().toString()));
			DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
			httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
			httpGet.setConfig(requestConfig);
			// 执行请求
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseContent;
	}
	
	/**
	 * 
	 * ----TODO：发送短信验证码
	 * 
	 */
	
	/**
	  * 方法名：sendMsgUtf8 
	  * 描述：    发送短信                  
	  * 参数：    @param Uid
	  * 参数：    @param Key
	  * 参数：    @param content
	  * 参数：    @param mobiles
	  * 参数：    @return 
	 * @return: int
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public int sendMsgUtf8(String Uid, String Key, String content, String mobiles) {
		Map maps = new HashMap();
		maps.put("Uid", Uid);
		maps.put("Key", Key);
		maps.put("smsMob", mobiles);
		maps.put("smsText", content);
		String result = sendHttpPost("http://utf8.sms.webchinese.cn", maps, "utf-8");
		return Integer.parseInt(result);
	}

	/**
	  * 方法名：sendMsgGbk 
	  * 描述：    发送短信                  
	  * 参数：    @param Uid
	  * 参数：    @param Key
	  * 参数：    @param content
	  * 参数：    @param mobiles
	  * 参数：    @return 
	 * @return: int
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public int sendMsgGbk(String Uid, String Key, String content, String mobiles) {
		Map maps = new HashMap();
		maps.put("Uid", Uid);
		maps.put("Key", Key);
		maps.put("smsMob", mobiles);
		maps.put("smsText", content);
		String result = sendHttpPost("http://gbk.sms.webchinese.cn", maps, "gbk");
		return Integer.parseInt(result);
	}

	/**
	  * 方法名：getErrorMsg 
	  * 描述：    回调                  
	  * 参数：    @param errorCode
	  * 参数：    @return 
	 * @return: String
	 */
	public String getErrorMsg(int errorCode) {
		if (errorCode == -1) {
			return "没有该用户账户";
		} else if (errorCode == -2) {
			return "接口密钥不正确";
		} else if (errorCode == -3) {
			return "短信数量不足";
		} else if (errorCode == -4) {
			return "手机号格式不正确";
		} else if (errorCode == -21) {
			return "MD5接口密钥加密不正确";
		} else if (errorCode == -11) {
			return "该用户被禁用";
		} else if (errorCode == -14) {
			return "短信内容出现非法字符";
		} else if (errorCode == -41) {
			return "手机号码为空";
		} else if (errorCode == -42) {
			return "短信内容为空";
		} else if (errorCode == -51) {
			return "短信签名格式不正确";
		} else if (errorCode == -6) {
			return "IP限制";
		} else {
			return "未知错误码:" + errorCode;
		}
	}
	
	/***
	  * 方法名：sedCode 
	  * 描述：    发送短信验证码                  
	  * 参数：    @param phone_num
	  * 参数：    @param session
	  * 参数：    @return 
	 * @return: String
	 */
	public static String sedCode(String phone_num,HttpSession session) {
		// 用户名
		String uid = "a760500758";
		// 接口安全秘钥
		String key = "d41d8cd98f00b204e980";
		// 手机号码，多个号码如13800000000,13800000001,13800000002
		String smsMob = phone_num;
		// 短信内容
		String smsText = "";
		//返回的信息
		String message = "";
		//生成的验证码
		String code = "";

		for (int i = 0; i < 6; i++) {
			int aCode = (int) (Math.random()*10);
			code +=aCode+"";
		}
		smsText = "你的验证码是：" + code + "，30分钟内有效，请勿透露给其他人。";
		
		HttpClientUtil client = HttpClientUtil.getInstance();
		// UTF发送短信
		int result = client.sendMsgUtf8(uid, key, smsText, smsMob);
		if (result > 0) {
			System.err.println("短信发送条数：" + result);
			message = "验证码已发送，30分钟内有效，请注意查收!";
		} else {
			System.err.println("异常原因："+client.getErrorMsg(result));
			message = "验证码已发送，30分钟内有效，请注意查收!";
			//message = "系统繁忙,请稍后重试!";
		}
		System.err.println("验证码："+code);
		//将验证码存入session
		session.setAttribute(phone_num, code);
		return message;
	}
}